<?php
/**
 * 导出cpl留资记录（德国菲斯曼活动：844）
 * 每天上午10点发送头一天的数据
 */
ini_set('display_errors', 1);
error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING ^ E_DEPRECATED);
ini_set('memory_limit', '1024M');

require_once '/data/wwwroot/g_vendor/autoload.php';

use Biz\model\activity\CplRecord;
use Biz\tools\Mail;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;

$startTime = date("Y-m-d", strtotime("-1 day", time()));
$endTime = date('Y-m-d');
$pageId = 844;
$pageTitle = '德国菲斯曼cpl活动' . $startTime . '-报名记录';

$where = [
    'page_id' => $pageId,
    'addtime[>=]' => $startTime,
    'addtime[<]' => $endTime,
];
$list = CplRecord::select('*', $where);
var_dump(CplRecord::log());
$data = [];
foreach ($list as $row) {
    $data[] = [
        'user_name' => $row['user_name'],
        'phone' => $row['phone'],
        'area' => $row['area'],
        'addtime' => $row['addtime']
    ];
}
$title = ['姓名', '手机号', '地区', '报名时间'];

$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$titCol = 'A';
foreach ($title as $key => $value) {
    // 单元格内容写入
    $sheet->setCellValue($titCol . '1', $value);
    $titCol++;
}
$sheet->getColumnDimension('A')->setWidth(12);
$sheet->getColumnDimension('B')->setWidth(15);
$sheet->getColumnDimension('C')->setWidth(20);
$sheet->getColumnDimension('D')->setWidth(25);
$row = 2; // 从第二行开始
foreach ($data as $item) {
    $dataCol = 'A';
    foreach ($item as $value) {
        // 单元格内容写入
        $sheet->setCellValue($dataCol . $row, $value);
        $dataCol++;
    }
    $row++;
}
$fileName = $pageTitle . '.xlsx';
$filePath = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $fileName;
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $fileName . '"');
header('Cache-Control: max-age=0');
header('Cache-Control: max-age=1');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header('Pragma: public'); // HTTP/1.0
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save($filePath);
var_dump('导出成功');

$email = ['tangyiwan@haohaozhu.com', 'liuqing@haohaozhu.com', 'yuyan@haohaozhu.com', 'cuijiaming@haohaozhu.com', 'lusinong@haohaozhu.com'];

Mail::send($email, $pageTitle, $pageTitle . '</br>报表见附件', $filePath);
var_dump('发送邮件成功');